package com.ukao.steward.ui.valetRunners.createOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.adapter.FragmentAdapter;
import com.ukao.steward.adapter.ShoppCountAdapter;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.bean.OrderDetailBean;
import com.ukao.steward.bean.ShoppingBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.bean.businessWholeBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.eventbus.ShoppChildEvent;
import com.ukao.steward.eventbus.ShoppEvent;
import com.ukao.steward.listener.OnItemChildClickListener;
import com.ukao.steward.pesenter.valetRunners.shoppingMallPesenter;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DensityUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.shoppingMallView;
import com.ukao.steward.widget.CustomPopWindow;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.submit_btn;
import static com.ukao.steward.consts.Constant.ARG_PARAM6;
import static com.ukao.steward.consts.Constant.ARG_PARAM7;
import static com.ukao.steward.consts.Constant.ARG_PARAM8;
import static com.ukao.steward.consts.Constant.ARG_PARAM9;


/**
 * 商城
 */
public class shoppingMallFragment extends MvpFragment<shoppingMallPesenter> implements shoppingMallView {
    // TODO: Rename parameter arguments, choose names that match

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.tab_title)
    TabLayout mTabLayout;
    @BindView(R.id.vp_pager)
    ViewPager mViewPager;

    Unbinder unbinder;
    @BindView(R.id.shoppin_mall_basket)
    ImageView shoppinMallBasket;
    @BindView(R.id.include_shopping_mall_bottom)
    RelativeLayout includeShoppingMallBottom;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.shopp_count)
    TextView shoppCount;
    @BindView(R.id.total_pice)
    TextView totalPice;
    @BindView(submit_btn)
    Button submitBtn;
    private int totalcount;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView closebtn;
    private TextView cleanbtn;
    private RecyclerView recyclerview;

    private CustomPopWindow mEnterFactoryWindow;
    private ArrayList<ShoppingBean> mShoppingDate = new ArrayList<>();
    private ShoppCountAdapter mShoppCountAdapter;
    private TextView popShoppCount;
    private int totalPices; /*总价格*/
    private TextView poptotalPice;
    private String zero;
    private TextView popshoppCount;
    private String userId;
    private String addressId;
    private String phone;
    private String name;
    private int cardDiscount=0;  /*用户折扣*/
    private boolean isValuationEnter;

    private OrderDetailBean mOrderDetailBean;
    private boolean isStorageEnter;
    private boolean isOrderStockInEnter;
    private String orderId;

    /**
     *
     * @param userId 用户id
     * @param addressId  用户地址
     * @param phone  手机号
     * @param name   名字
     * @param cardDiscount  用户会员卡折扣
     *  @param isStorageEnter  入库下单进入
     *  @param isStorageEnter  是否是订单详情进入入库
     * @return
     */
    public static shoppingMallFragment newInstance(String userId, String addressId,String  phone,String  name,int  cardDiscount,boolean  isStorageEnter) {
        shoppingMallFragment fragment = new shoppingMallFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, userId);
        args.putString(ARG_PARAM2, addressId);
        args.putString(Constant.ARG_PARAM3, phone);
        args.putString(Constant.ARG_PARAM4, name);
        args.putInt(Constant.ARG_PARAM5, cardDiscount);
        args.putBoolean(ARG_PARAM8, isStorageEnter);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     *
     * @param isValuationEnter   是否是计价进入
     * @param mOrderDetailBean   订单详情数据
     * @return
     */
    public static shoppingMallFragment newInstance(boolean  isValuationEnter,OrderDetailBean    mOrderDetailBean,boolean   isOrderStockInEnter   ) {
        shoppingMallFragment fragment = new shoppingMallFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM6, isValuationEnter);
        args.putParcelable(ARG_PARAM7, mOrderDetailBean);
        args.putBoolean(ARG_PARAM9, isOrderStockInEnter);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isValuationEnter= getArguments().getBoolean(Constant.ARG_PARAM6,false);
            if (isValuationEnter){
                mOrderDetailBean= getArguments().getParcelable(ARG_PARAM7);
                isOrderStockInEnter= getArguments().getBoolean(Constant.ARG_PARAM9,false);
                orderId=mOrderDetailBean.getId()+"";
                userId=mOrderDetailBean.getUserId();
            }else{
                userId= getArguments().getString(ARG_PARAM1);
                addressId= getArguments().getString(ARG_PARAM2);
                phone= getArguments().getString(Constant.ARG_PARAM3);
                name= getArguments().getString(Constant.ARG_PARAM4);
                cardDiscount= getArguments().getInt(Constant.ARG_PARAM5);
                isStorageEnter= getArguments().getBoolean(Constant.ARG_PARAM8,false);

            }



        }
    }

    @Override
    protected shoppingMallPesenter createPresenter() {
        return new shoppingMallPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_shopping_mall, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mvpPresenter.businessWholeTab();
    }

    @Override
    protected void initView() {

        zero=getResources().getString(R.string.zero);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("商城列表");
        chageInit();



    }

    /**
     * 修改初始化
     */
    private void chageInit() {
        if (isValuationEnter&&mOrderDetailBean!=null){
           if (!CheckUtils.isEmpty(mOrderDetailBean.getmClothlist())){
               for (StringBean item : mOrderDetailBean.getmClothlist()) {
                   ShoppingBean   mstringBean=null;

                   if (!CheckUtils.isEmpty(item.getMercBusinessId())){
                       mstringBean=new  ShoppingBean(item.getMercBusinessId(),item.getProTypeId(),item.getBusinessId(),
                               item.getBusinessName(),item.getId(),item.getCnt() ,item.getName(),
                               item.getName(),item.getPrice(),item.getDiscount(),item.getServiceName(),item.getProServiceId());
                       mShoppingDate.add(mstringBean);

                   }else if (!isOrderStockInEnter){
                          mstringBean=new  ShoppingBean(item.getId(),item.getCnt() ,item.getName(),
                               item.getName(),item.getPrice(),item.getDiscount(),item.getSrvName(),item.getSrvId());
                       mShoppingDate.add(mstringBean);

                   }


               }
               calculateTotalPice();
               fillPice();
           }

        }
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.back_btn, R.id.shoppin_mall_layout, submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;

            case submit_btn:
                createOrder(mShoppingDate);


                break;
            case R.id.shoppin_mall_layout:
                showPopEnterFactory();
                break;



        }
    }




    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ShoppEvent event) {
        switch (event.getMessage()) {
            case   CHAGE_ADD_COUNT:  /*修改添加*/

                ShoppingBean mChageShoppingBean = (ShoppingBean) event.getData();
                for (int i = 0; i < mShoppingDate.size(); i++) {
                    ShoppingBean mitem = mShoppingDate.get(i);
                    if (mitem.getId().equals(mChageShoppingBean.getId())) {
                        mShoppingDate.set(i,mChageShoppingBean);

                    }
                }
                if (!mShoppingDate.contains(mChageShoppingBean)){
                    mShoppingDate.add(mChageShoppingBean);
                }

                calculateTotalPice();
                fillPice();

                break;
            case ADD_COUNT:/*添加*/
                ShoppingBean mShoppingBean = (ShoppingBean) event.getData();
                L.i("  mShoppingBean.getTypeId()="+  mShoppingBean.getTypeId());
                if (!mShoppingDate.contains(mShoppingBean)) {
                    mShoppingDate.add(mShoppingBean);
                }

                calculateTotalPice();
                fillPice();
                break;
            case FINISH:
               if ( isAdded()){
                   finish();
               }

                break;


        }
    }

    private void calculateTotalPice() {
        totalcount = 0;
        totalPices=0;
        for (ShoppingBean shoppingBean : mShoppingDate) {
            totalcount = totalcount + shoppingBean.getCount();
           int    pice=shoppingBean.getPrice()*shoppingBean.getCount();
            totalPices=totalPices+pice;
        }
    }

    private void fillPice() {
        if (totalcount != 0) {
            shoppCount.setVisibility(View.VISIBLE);
            shoppCount.setText(String.valueOf(totalcount));
            totalPice.setText("￥"+ CheckUtils.isEmptyNumber(totalPices));
            if (!CheckUtils.isNull(popshoppCount)){
                popShoppCount.setVisibility(View.VISIBLE);
                popShoppCount.setText(String.valueOf(totalcount));
                poptotalPice.setText("￥"+CheckUtils.isEmptyNumber(totalPices));
            }
        } else {
            totalPice.setText(zero);
            shoppCount.setVisibility(View.GONE);
            if (!CheckUtils.isNull(popshoppCount)){
                poptotalPice.setText(zero);
                popShoppCount.setVisibility(View.GONE);
            }
        }
    }


    public CustomPopWindow showPopEnterFactory() {
        View contentView = LayoutInflater.from(_mActivity).inflate(R.layout.popwindow_shop_layout, null);
        this.recyclerview = (RecyclerView) contentView.findViewById(R.id.recycler_view);
        this.cleanbtn = (TextView) contentView.findViewById(R.id.clean_btn);
        this.closebtn = (TextView) contentView.findViewById(R.id.close_btn);
        this.popShoppCount = (TextView) contentView.findViewById(R.id.shopp_count);
        Button submitBtn = (Button) contentView.findViewById(R.id.submit_btn);
         poptotalPice= (TextView) contentView.findViewById(R.id.total_pice);
        popshoppCount= (TextView) contentView.findViewById(R.id.shopp_count);


        if (totalcount != 0) {
            popShoppCount.setVisibility(View.VISIBLE);
            popShoppCount.setText(String.valueOf(totalcount));
            poptotalPice.setText("￥"+CheckUtils.isEmptyNumber(totalPices));
        } else {
            popShoppCount.setVisibility(View.GONE);
            poptotalPice.setText(zero);
        }

        submitBtn.setOnClickListener(mOnClickListener);
        closebtn.setOnClickListener(mOnClickListener);
        cleanbtn.setOnClickListener(mOnClickListener);
        initLinearRecyclerView(recyclerview);
        mShoppCountAdapter = new ShoppCountAdapter(_mActivity, mShoppingDate);
        mShoppCountAdapter.setOnItemChildClickListener(mOnItemChildClickListener);
        recyclerview.setAdapter(mShoppCountAdapter);
        mEnterFactoryWindow = new CustomPopWindow.PopupWindowBuilder(_mActivity)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .size(ViewGroup.LayoutParams.MATCH_PARENT, (int) (DensityUtils.getScreenH()*0.65))//显示大小
                .create()
                .showAtLocation(includeShoppingMallBottom, Gravity.BOTTOM, 0, 0);


        return mEnterFactoryWindow;
    }

    private OnItemChildClickListener mOnItemChildClickListener;

    {
        mOnItemChildClickListener = new OnItemChildClickListener() {
            @Override
            public void onChildItemClick(int id, int pos, Object item) {
                ShoppingBean items = mShoppCountAdapter.getItem(pos);
                switch (id) {
                    case R.id.subtract_btn:
                        if (items.getCount() != 0){
                            items.setCount(items.getCount() - 1);
                            mShoppCountAdapter.notifyDataSetChanged();
                            totalPices=totalPices- items.getPrice();
                            ShoppChildEvent.postHasData(ShoppChildEvent.Message.SUBTRACT_COUNT,items);
                            if (items.getCount()==0){
                                mShoppingDate.remove(items);
                                mShoppCountAdapter.getDataList().remove(items);
                                mShoppCountAdapter.notifyDataSetChanged();
                            }

                        }

                        break;
                    case R.id.add_btn:
                        items.setCount(items.getCount() + 1);
                        mShoppCountAdapter.notifyDataSetChanged();
                        totalPices=totalPices+items.getPrice();
                        ShoppChildEvent.postHasData(ShoppChildEvent.Message.ADD_COUNT,items);
                        break;

                }

                   totalcount=0;
                for (ShoppingBean shoppingBean : mShoppCountAdapter.getDataList()) {
                    totalcount=totalcount+shoppingBean.getCount();
                }

                fillPice();

            }
        };
    }


    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.clean_btn:
                    totalPices=0;
                    totalcount=0;
                    mShoppCountAdapter.clear();
                    mShoppCountAdapter.notifyDataSetChanged();
                    mShoppingDate.clear();
                    fillPice();
                    ShoppChildEvent.postNoData(ShoppChildEvent.Message.CLEAR_ALL);
                    break;
                case R.id.close_btn:
                    mEnterFactoryWindow.dissmiss();
                    break;
                case R.id.submit_btn:
                    List<ShoppingBean> mData = mShoppCountAdapter.getDataList();
                    createOrder(mData);
                    break;


            }


        }
    };

    private   void  createOrder(  List<ShoppingBean> mData){
        if (CheckUtils.isEmpty(mData)||totalcount==0){
            T.show("请选择商品");
            return;
        }


      mvpPresenter.createOrder( mData,isValuationEnter);
    }


    /**
     * 生成订单
     * @param mBusinessArray
     * @param mStringBeanData
     * @param service
     */
    @Override
    public void createOrderSucceed(String mBusinessArray,ArrayList<StringBean>   mStringBeanData,String  service) {
        if (!CheckUtils.isNull(mEnterFactoryWindow)&&mEnterFactoryWindow.getPopupWindow().isShowing()){
            mEnterFactoryWindow.dissmiss();
        }


            if (isAdded()){
                start(CreateOrderFragment.newInstance(addressId, userId, String.valueOf(totalcount), mBusinessArray,
                        mStringBeanData, String.valueOf(totalPices), service, phone, name, isStorageEnter), SINGLETASK);
            }







    }


    /**
     * 计价格
     * @param mStringBeanData
     */
    @Override
    public void valuationSucceed(ArrayList<StringBean> mStringBeanData) {
        if (!CheckUtils.isNull(mEnterFactoryWindow)&&mEnterFactoryWindow.getPopupWindow().isShowing()){
            mEnterFactoryWindow.dissmiss();
        }
        if (isAdded()){
            startForResult(CreateOrderFragment.newInstance( mOrderDetailBean,String.valueOf(totalcount),String.valueOf(totalPices),
                    mStringBeanData,isValuationEnter,isOrderStockInEnter ),Constant.REQUEST_CODE);
        }

    }



    @Override
    public void businessWholeSucceed(List<businessWholeBean> mIncomeDetailbBean) {
        if (CheckUtils.isEmpty(mIncomeDetailbBean)) return;
        initViewPager(mIncomeDetailbBean);




    }




    private void initViewPager(List<businessWholeBean> mIncomeDetailbBean) {
        List<Fragment> fragments = new ArrayList<>();
        for (businessWholeBean item : mIncomeDetailbBean) {
            mTabLayout.addTab(mTabLayout.newTab().setText(item.getName()));
            ArrayList<ShoppingBean>     mChageData= isValuationEnter ==true? mShoppingDate : null;
            ArrayList<businessWholeBean.TypeListBean> mData = (ArrayList<businessWholeBean.TypeListBean>) item.getTypeList();
            fragments.add(shoppListFragment.newInstance(mData, item.getBusinessId(),item.getName(),mChageData,isValuationEnter,
                    userId,isStorageEnter,item.getMercBusinessId(),isOrderStockInEnter,orderId));
        }

        FragmentAdapter mFragmentAdapteradapter = new FragmentAdapter(getChildFragmentManager(), fragments, mIncomeDetailbBean);
        mViewPager.setAdapter(mFragmentAdapteradapter);
        mViewPager.setOffscreenPageLimit(mIncomeDetailbBean.size() - 1);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabsFromPagerAdapter(mFragmentAdapteradapter);

    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    setFragmentResult(RESULT_OK, null);
                    finish();

                    break;
            }

        }
    }

}
